package com.musemun.util;

import org.apache.poi.util.IOUtils;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;
import org.springframework.util.ResourceUtils;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.util.LinkedList;
import java.util.List;
import java.util.UUID;
import java.util.concurrent.ExecutorService;
/**
 * @description:
 *         这是我写的一个不成熟的文件上传工具类 不过能用后期会做修改
 * @author winner
 * @date 2020/4/14
 */
@Component
public class UploadFileUtils{
    private static String PATH=null;

    static {
        try {
            PATH= ResourceUtils.getURL("classpath:").getPath() + "/static/";
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
    }

    /**
     * description:
     *        传入文件夹名和文件，保存至那个文件夹
     * @param directoryName 需要上传到哪个文件家
     * @param uploads 上传的文件
     * @return int 返回上传成功的条数
     */
    public static void upload(String directoryName, MultipartFile[] uploads,List<String> fileList) throws IOException {

        String path = PATH + directoryName;
        File directory = new File(path);
//        if (!directory.exists()) {
//            directory.mkdirs();
//        }
        int flag=0;
        for (MultipartFile upload : uploads) {
            String filename=fileList.get(flag++);
            upload.transferTo(new File(path, filename));
        };
    }



    /**
     *
     *
     * @param directoryName   要保存的文件加
     * @param upload  下载的文件
     * @param fileName  需要保存的文件名
     * @return java.lang.String
     */
    public static void upload(String directoryName, MultipartFile upload,String fileName) throws IOException {
        String path = PATH + directoryName;
//        File directory = new File(path,fileName);
//        if (!directory.exists()) {
//            directory.mkdirs();
//        }
        upload.transferTo(new File(path, fileName));
    }

    //下载
    public static void downloadFileAction(String path,HttpServletRequest request, HttpServletResponse response) {
        response.setCharacterEncoding(request.getCharacterEncoding());
        response.setContentType("application/octet-stream");
        FileInputStream fis = null;
        try {
            File file = new File(path);
            fis = new FileInputStream(file);
            response.setHeader("Content-Disposition", "attachment; filename=" + file.getName());
            IOUtils.copy(fis, response.getOutputStream());
            response.flushBuffer();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (fis != null) {
                try {
                    fis.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}

